package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(int roleId) {
        return permissionDao.findPermissionIdsByRoleId(roleId);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //获取当前页
        Integer currentPage = queryPageBean.getCurrentPage();
        //获取当前页记录条数
        Integer pageSize = queryPageBean.getPageSize();
        //获取查询条件  拼接字符串 为模糊查询做准备
        String queryString = queryPageBean.getQueryString();
        if (queryString != null && !queryString.equals("null")) {
            queryString = "%" + queryString + "%";
        } else {
            queryString = "%%";
        }
        //分页插件，会在执行sql之前将分页关键字追加到SQL后面
        PageHelper.startPage(currentPage , pageSize);
        Page<Permission> page = permissionDao.findByCondition(queryString);
        return new PageResult(page.getTotal() , page.getResult());
    }

    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    @Override
    public void delete(Integer id) {
        Long count = permissionDao.findCountById(id);
        if (count > 0) {
            //权限关联了角色信息，不能删除
            throw new RuntimeException("该权限关联了角色信息，不能删除");
        } else {
            permissionDao.delete(id);
        }
    }

    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }
}
